﻿#ifndef DESCRIPTION_H
#define DESCRIPTION_H

#include <QObject>
#include <QXmlStreamWriter>
#include "device.h"
#include "objectfactory.h"
#include "step.h"
#include <QThread>
#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonArray>


class Description;

class DescriptionInitThread : public QThread {
    Q_OBJECT
public:
    explicit DescriptionInitThread(QObject *parent = nullptr){
    }

private:
    QList<Device *> m_pDevices;

public:

    void SetDevices(QList<Device *> devices){
        m_pDevices = devices;
    }

public:
    void run() override {
        // 在这里执行你的线程任务
        foreach (Device *pDevice, m_pDevices) {
            pDevice->initDevice();
        }

        qDebug() << "InitAllDevices is finished!";
    }
};

/**
 * @brief The DescriptionRunThread class
 * 运行Description的子线程
 */
class DescriptionRunThread : public QThread {
    Q_OBJECT
public:
    explicit DescriptionRunThread(QObject *parent = nullptr) : m_isRunning(false){
    }

private:
    QList<Step *> m_pSteps;
    bool m_isRunning;

public:
    void Stop(){
        m_isRunning = false;
    }

    void SetSteps(QList<Step *> steps){
        m_pSteps = steps;
    }

public:
    void run() override {
        // 在这里执行你的线程任务

        m_isRunning = true;
        foreach (Step *pStep, m_pSteps) {
            if(!m_isRunning){
                pStep->Stop();
                break;
            }
            pStep->run();
            qDebug() << "Step is Running!" ;
            QThread::msleep(10);
        }
        qDebug() << "Run is finished!";
    }
};

class Description : public QObject
{
    Q_OBJECT
public:
    Description();
    ~Description(){
        delete m_DescriptionRunThread;
    }

private:
    QList<Device *>     m_pDevices;
    QList<Step *>       m_pSteps;
    bool                m_isAllInitialized;
    bool                m_isRunning;


    void                InitObjectFactory();

public:
    Device *FindDeviceById(QString strID);
    QList<Step *>       GetSteps(){return m_pSteps;}
    QList<Device *>     GetDevices(){return m_pDevices;}
    void                SetAllInitialized(bool isInitialized){
        m_isAllInitialized = isInitialized;
    }

public:
    void clear();

public:
    void AddDevice(Device *pDevice) { m_pDevices.append(pDevice); }
    void AddStep(Step *pStep) { m_pSteps.append(pStep); }

public:
    bool writeXML(const QString &filePath);
    bool ReadXML(const QString &filePath);
    bool ReadXML(QXmlStreamReader &xmlReader);

    void initAllDevices();
    void uninitAllDevices();
    void run();
    void stop();
    void test();
    QList<Device *> pDevices() const;
    QList<Step *> pSteps() const;

private:
    DescriptionRunThread *m_DescriptionRunThread;

public slots:
    // 接收到虚拟设备的命令
    void ReceviceCmdFromVirtualDevice(QVariant variant);

signals:
    void SendCmdToMainWindow(QVariant variant);
};

#endif // DESCRIPTION_H
